
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'HaiFeng'
__mtime__ = '2016/9/13'
"""

import _thread
from time import sleep

from py_ctp.ctp_struct import *
from py_ctp.quote import Quote

from py_ctp.src.trade import Trade


class Dome4:
    def __init__(self):
        self.Session = ''
        self.q = Quote()
        self.t = Trade()
        self.req = 0
        self.ordered = False

    def q_OnFrontConnected(self):
        print('行情前置主机链接之后开始进行行情登陆')
        self.q.ReqUserLogin(BrokerID='9999', UserID='xxx', Password='***')

    def q_OnRspUserLogin(self, rsp, info, req, last):
        print('行情登陆成功 信息如下 之后开始订阅合约rb1710')
        print(rsp)

        # insts = create_string_buffer(b'cu', 5)
        self.q.SubscribeMarketData('p1709')

    def q_OnTick(self, tick):
        f = CThostFtdcMarketDataField()
        f = tick
        #print('订阅的合约tick为')
        #print(tick)

        # if not self.ordered:
        #     print('如果没有发过单子那么直接新线程发送一个单子')
        #     _thread.start_new_thread(self.Order, (f,))
        #     self.ordered = True

    def Order(self, f):
        self.req += 2
        self.t.ReqOrderInsert(
            BrokerID='9999',
            InvestorID='051355',
            InstrumentID=f.getInstrumentID(),
            OrderRef='{0:>12}'.format(self.req),
            UserID='051355',
            OrderPriceType=OrderPriceTypeType.LimitPrice,
            Direction=DirectionType.Buy,
            CombOffsetFlag=OffsetFlagType.Open.__char__(),
            CombHedgeFlag=HedgeFlagType.Speculation.__char__(),
            LimitPrice=f.getLastPrice() - 5000,
            VolumeTotalOriginal=1,
            TimeCondition=TimeConditionType.GFD,
            # GTDDate=''
            VolumeCondition=VolumeConditionType.AV,
            MinVolume=1,
            ContingentCondition=ContingentConditionType.Immediately,
            StopPrice=0,
            ForceCloseReason=ForceCloseReasonType.NotForceClose,
            IsAutoSuspend=0,
            IsSwapOrder=0,
            UserForceClose=0)

    def OnFrontConnected(self):
        print('前置主机链接成功开始进行登陆')
        self.t.ReqUserLogin(BrokerID='9999', UserID='051355', Password='888888')

    def OnRspUserLogin(self, rsp, info, req, last):
        i = CThostFtdcRspInfoField()
        i = info
        print(rsp)
        print(req)
        print('登陆信息 如果成功那么进行账单确认'+i.getErrorMsg())



        if i.getErrorID() == 0:
            self.Session = rsp.getSessionID()
            self.t.ReqSettlementInfoConfirm(BrokerID='9999', InvestorID='051355')

    def StartQuote(self):
        api = self.q.CreateApi()
        spi = self.q.CreateSpi()
        self.q.RegisterSpi(spi)

        self.q.OnFrontConnected = self.q_OnFrontConnected
        self.q.OnRspUserLogin = self.q_OnRspUserLogin
        self.q.OnRtnDepthMarketData = self.q_OnTick

        self.q.RegCB()

        self.q.RegisterFront('tcp://180.168.146.187:10010')
        self.q.Init()
        self.q.Join()

    def OnRspOrderInsert(self, pInputOrder=CThostFtdcInputOrderField, pRspInfo=CThostFtdcRspInfoField, nRequestID=int,
                         bIsLast=bool):
        f = CThostFtdcRspInfoField()

        f = pRspInfo
        print('执行了OnRspOrderInsert')
        print(pRspInfo)
        print(pInputOrder)
        print(f.getErrorMsg())

    def OnRtnOrder(self, pOrder=CThostFtdcOrderField):
        print('执行了OnRtnOrder')
        print(pOrder)

        #演示撤单教程
        if pOrder.getSessionID() == self.Session and pOrder.getOrderStatus() == OrderStatusType.NoTradeQueueing:
            print('执行了撤单')
            self.t.ReqOrderAction(
                '9999', '051355',
                InstrumentID=pOrder.getInstrumentID(),
                OrderRef=pOrder.getOrderRef(),
                FrontID=pOrder.getFrontID(),
                SessionID=pOrder.getSessionID(),
                ActionFlag=ActionFlagType.Delete)

    def OnRspSettlementInfoConfirm(self, pSettlementInfoConfirm=CThostFtdcSettlementInfoConfirmField,
                                   pRspInfo=CThostFtdcRspInfoField, nRequestID=int, bIsLast=bool):
        print('投资者信息确认完成 在一个新线程里面进行行情初始化')
        _thread.start_new_thread(self.StartQuote, ())

    def Qry(self):
        sleep(1.1)
        self.t.ReqQryInstrument()
        while True:
            sleep(1.1)
            self.t.ReqQryTradingAccount('9999', '051355')
            sleep(1.1)
            #当前时侯的昨持仓=总持仓-今持仓。YdPosition := Position - TodayPosition。
            self.t.ReqQryInvestorPosition('9999', '051355')
            return

    def OnRtnInstrumentStatus(self, pInstrumentStatus=CThostFtdcInstrumentStatusField):
        """交易所状态变化"""
        pass


    def OnRspQryInstrument(self, pInstrument=CThostFtdcInstrumentField, pRspInfo=CThostFtdcRspInfoField, nRequestID=int,
                           bIsLast=bool):
        """查询合约返回"""
        # print (pInstrument)
        # print(pRspInfo)
        # print(nRequestID)
        # print(bIsLast)
        #pass

    def OnRspQryTradingAccount(self, pTradingAccount=CThostFtdcTradingAccountField, pRspInfo=CThostFtdcRspInfoField,
                               nRequestID=int, bIsLast=bool):
        # print(
        #     '方法 OnRspQryTradingAccount:, pTradingAccount = CThostFtdcTradingAccountField, pRspInfo = CThostFtdcRspInfoField, nRequestID = int, bIsLast = bool')
        # print(pTradingAccount)
        # print(pRspInfo)
        # print(nRequestID)
        # print(bIsLast)
        pass
    def OnRspQryInvestorPosition(self,pInvestorPosition=CThostFtdcInvestorPositionField,
                                 pRspInfo=CThostFtdcRspInfoField, nRequestID=int, bIsLast=bool):
        print(
            '方法 OnRspQryInvestorPosition:, ,pInvestorPosition=CThostFtdcInvestorPositionField,pRspInfo=CThostFtdcRspInfoField, nRequestID=int, bIsLast=bool')
        """持仓返回情况"""
        #print("持仓返回");
        #print(pInvestorPosition)
        pass

    def Run(self):
        # CreateApiʱܡԃսlogĿ¼,ѨҪ՚ԌѲĿ¼ЂԴݨ**׸؇dllЂ**
        api = self.t.CreateApi()
        spi = self.t.CreateSpi()
        self.t.RegisterSpi(spi)

        self.t.OnFrontConnected = self.OnFrontConnected
        self.t.OnRspUserLogin = self.OnRspUserLogin
        self.t.OnRspSettlementInfoConfirm = self.OnRspSettlementInfoConfirm
        self.t.OnRtnInstrumentStatus = self.OnRtnInstrumentStatus  #会通知当前交易所状态变化
        self.t.OnRspOrderInsert = self.OnRspOrderInsert
        self.t.OnRspQryInstrument = self.OnRspQryInstrument
        self.t.OnRspQryTradingAccount=self.OnRspQryTradingAccount
        self.t.OnRspQryInvestorPosition=self.OnRspQryInvestorPosition

        self.t.OnRtnOrder = self.OnRtnOrder
        _thread.start_new_thread(self.Qry, ())

        self.t.RegCB()

        self.t.RegisterFront('tcp://180.168.146.187:10000')
        self.t.Init()
        self.t.Join()


if __name__ == '__main__':
    t = Dome4()
    t.Run()
    input()

